<template>
<div>
  <el-row>
    <img  crossOrigin="anonymous" :src="url" alt="">
  </el-row>
  <dialog-form ref="dialog" :form="form" :showDialog.sync="showDialog" v-on:close="showDialog = false" v-on:submit="closeDialog"></dialog-form>
  <el-row>
    <el-button v-on:click="addImg" >添加图片</el-button>
    <el-button v-on:click="addText" >添加文字</el-button>
    <el-button v-on:click="addWater" >添加水印</el-button>
    <el-button v-on:click="clear" >清空</el-button>
    <el-button v-on:click="importImg" >导出2</el-button>
  </el-row>



  <p>{{qiniuUrl}}</p>
</div>
</template>

<script>
  import DialogForm from './Form'
  import { MCanvas } from 'mcanvas'
  import loadEvents from '../../Utils/Loading'
  import md5 from 'js-md5';
  let Base64 = require('js-base64').Base64;
  // 创建画布，初始化 canvas；
  let mc = new MCanvas({
    width: 500,
    height: 500,
    backgroundColor: 'black',
  })
  let loading = new loadEvents();
  export default {
    name: 'test',
    data(){
      return{
        url:'',
        token:'',
        qiniuaddr: "https://supimage.miniprogramhacker.cn", // 七牛云的图片外链地址
        domain: "https://upload-z2.qiniup.com", // 七牛云的上传地址（华南区）
        qiniuUrl:'',
        form: {
          imgUrl:'',
          imgWidth:'50%',
          xLocation:'0',
          yLocation:'0',
          scale:'1'
        },
        showDialog:false
      }
    },
    components:{
      DialogForm
    },
    mounted: function () {
      this.getQiniuToken();
      this.initCanvas()
    },
    methods:{

      closeDialog(){
        // alert(1234)
        this.showDialog = false
        var scr3 = 'https://supimage.miniprogramhacker.cn/beauty/faceWash/GiorgioArmanishsrdzcg_3.jpeg'
        var src = this.form.imgUrl + "?timeStamp=" + new Date().getTime();
        if (src.indexOf("http") != 0){
          this.$message({
            type:'info',
            message:'图片地址不是网络地址'
          });
          return;
        }

        // add 添加图片素材基础函数；
        mc.add(src, {
          width: this.form.imgWidth,
          pos: {
            x: this.form.xLocation,
            y: this.form.yLocation,
            scale: this.form.scale,
            rotate: 1,
          },
        })
        this.drawCanvas()
      },
      initCanvas(){
        var src = 'https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=2534506313,1688529724&fm=26&gp=0.jpg' + "?timeStamp=" + new Date().getTime();
        var src = 'https://supimage.miniprogramhacker.cn/animal/dog/guibinq_2.jpg'
        var scr3 = 'https://supimage.miniprogramhacker.cn/beauty/faceWash/GiorgioArmanishsrdzcg_3.jpeg'
        mc.background(src, {
          left: 0,
          top: 0,
          color: '#000000',
          type: 'origin',
        })
        this.drawCanvas()
      },
      drawCanvas(){

        loading.open()
        mc.draw(b64 => {
          this.url = b64
          loading.close()
        }).catch(error => {
          loading.close()
          this.$message(
            {
              type:'info',
              message:'图片合成失败'
            }
          )
        })
      },

      dataURLtoBlob(dataurl){
        var arr = dataurl.split(','),
          mime = arr[0].match(/:(.*?);/)[1],
          bstr = atob(arr[1]),
          n = bstr.length,
          u8arr = new Uint8Array(n);
        while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
        }
        return new Blob([u8arr], { type: mime });
      },
      blobToFile(theBlob, fileName){
        theBlob.lastModifiedDate = new Date();
        theBlob.name = fileName;
        return theBlob;
      },
      importImg(){
        loading.open()
        var blob = this.dataURLtoBlob(this.url);
        var file = this.blobToFile(blob, "bcd");
        this.uploadImgToQiniu(file)
      },
      //上传图片到七牛
      uploadImgToQiniu(file){
        let randText = this.randomText(5)
        let timestamp = new Date().getTime()
        let baseN = Base64.encode(this.randomText(9))
        let mdName = md5(baseN+timestamp+randText)
        let key = 'testPic/'+mdName

        const axiosInstance = this.$axios.create({withCredentials: false});    //withCredentials 禁止携带cookie，带cookie在七牛上有可能出现跨域问题
        let data = new FormData();
        data.append('token', this.token);     //七牛需要的token，叫后台给，是七牛账号密码等组成的hash
        data.append('file', file);
        data.append('key', key)

        axiosInstance({
          method: 'POST',
          url: this.domain,  //上传地址
          data: data,
          timeout:30000,      //超时时间，因为图片上传有可能需要很久
        }).then(data =>{
          this.qiniuUrl = this.qiniuaddr+ "/"+key
          loading.close()
          this.$message(
            {
              type:'success',
              message:'上传成功'
            }
          )
        }).catch(function(err) {

          loading.close()
          this.$message(
            {
              type:'info',
              message:'上传失败'
            }
          )
          //上传失败
        });
      },
      //请求后台拿七牛云token
      getQiniuToken() {
        this.getAxios('public/qiniuToken').then(res => {
          this.token = res.data;
        });
      },
      addImg(){
        this.showDialog = true
      },
      addText(){
        mc.text('郭东东<br><s>啊啊啊</s>',{
          width: '300px',
          align: 'center',
          pos: {
            x:100,
            y:100,
          },
        })
        this.drawCanvas()
      },
      addWater(){

      },
      clear(){
        mc.clear()
        this.initCanvas();
      }
    }
  }
</script>

<style scoped>
  img { max-width: 20%; height: auto; width: auto; width: auto; }
</style>
